package com.cyandpos.pad.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cyandpos.pad.R;
import com.cyandpos.pad.common.commondata.BaseResponse;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.offline.offlinedb.OfflineManager;
import com.cyandpos.pad.offline.upload.OfflineUploadFailAdapter;
import com.cyandpos.pad.offline.upload.TicketOffline;
import com.cyandpos.pad.posdata.LoadConfig;
import com.cyandpos.pad.utils.ToastUtils;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class OfflineUploadDataActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.ibback_offline_upload)
    ImageButton ibbackOfflineUpload;//返回
    @BindView(R.id.tv_upload_totalNum_offline)
    TextView tvUploadTotalNumOffline;//待上传条数
    @BindView(R.id.tv_upload_successNum_offline)
    TextView tvUploadSuccessNumOffline;//上传成功条数
    @BindView(R.id.tv_upload_failNum_offline)
    TextView tvUploadFailNumOffline;//上传失败条数
    @BindView(R.id.lv_upload_fail_data_offline)
    ListView lvUploadFailDataOffline;//上传失败详情
    @BindView(R.id.btn_upload_offline)
    LinearLayout btnUploadOffline;//开始上传
    @BindView(R.id.ll_upload_fail_info_offline)
    LinearLayout llUploadFailInfo;//上传失败详情

    List<TicketOffline> needUploadList =new ArrayList<>();
    List<TicketOffline> successUploadList =new ArrayList<>();
    List<TicketOffline> failUploadList =new ArrayList<>();

    private ProgressDialog mProgressDialog;//等待框
    private Dialog mUploadDialog;// 进度弹框
    private ProgressBar mProgressBar;// 进度控件
    private TextView mTextView;

    private static final int UPLOADING = 1;// 正在上传中
    private static final int UPLOAD_FINISH = 2;// 上传完成
    private int mProgress=0;// 上传进度框的更新进度
    int countUpload = 0;//已经上传条数
    private OfflineUploadFailAdapter adapter;

    private Handler mUpdateProgressHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOADING:
                    // 更新进度框
                    mProgressBar.setProgress(mProgress);
                    mTextView.setText(mProgress + "%");
                    break;
                case UPLOAD_FINISH:
                    // 取消进度框
                    mUploadDialog.dismiss();
                    //更新界面信息
                    initData();
                    if(failUploadList.size()>0)
                        llUploadFailInfo.setVisibility(View.VISIBLE);
                    //listview显示数据
                    adapter.notifyDataSetInvalidated();
                    break;
                    default:
                        break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offline_upload_data);
        ButterKnife.bind(this);
        initData();
        adapter = new OfflineUploadFailAdapter(this,failUploadList);
        lvUploadFailDataOffline.setAdapter(adapter);
        querySqliteDabaseOfflineTradeNum();
        btnUploadOffline.setOnClickListener(this);
        ibbackOfflineUpload.setOnClickListener(this);
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setCancelable(false);
    }

    private void initData() {
        tvUploadTotalNumOffline.setText((needUploadList.size() - successUploadList.size())+" 条");
        tvUploadSuccessNumOffline.setText(successUploadList.size()+" 条");
        tvUploadFailNumOffline.setText(failUploadList.size()+" 条");
    }

    private void querySqliteDabaseOfflineTradeNum() {
        needUploadList = OfflineManager.queryOfflineUploadData();
        if(needUploadList.size()>0){
            initData();
        }else{
            ToastUtils.showMsg("暂无脱机数据上传！");
            initData();
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_upload_offline:{//上传按钮
                if(failUploadList!=null&&failUploadList.size()>0){
                    ToastUtils.showMsg("有"+failUploadList.size()+"条上传失败,请关闭重新上传这"+failUploadList.size()+"条");
                }else {
                    if (needUploadList.size() - successUploadList.size() > 0) {
                        showUploadDialog();
                    } else {
                        ToastUtils.showMsg("暂无脱机数据上传！");
                    }
                }
            }
            break;
            case  R.id.ibback_offline_upload:{//返回按键
                needUploadList.clear();
                successUploadList.clear();
                failUploadList.clear();
                initData();
                adapter.notifyDataSetInvalidated();
                finish();
            }
            break;
        }

    }
    private void showUploadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(OfflineUploadDataActivity.this);
        builder.setTitle("正在上传小票，请稍等");
        View view = LayoutInflater.from(OfflineUploadDataActivity.this).inflate(R.layout.dialog_update_progress, null);
        mProgressBar = (ProgressBar) view.findViewById(R.id.id_update_progress);
        mTextView = (TextView) view.findViewById(R.id.id_update_textview);
        builder.setView(view);
        mUploadDialog = builder.create();
        mUploadDialog.show();
        // 上传本地小票数据
        uploadOfflineTikcet();

    }

    private void uploadOfflineTikcet() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    final int lengthTotal = needUploadList.size();
                    for(TicketOffline ticket :needUploadList){
                        upload_offline_ticket(ticket, new UpLoadDataListener() {
                            @Override
                            public void onUploadSuccess(TicketOffline ticket) {
                                successUploadList.add(ticket);
                                countUpload ++;
                                // 获取当前下好的文件占总文件的多少比率
                                mProgress = (int) (((float) countUpload / lengthTotal) * 100);
                                // 给Handler发送信息更新进度条
                                mUpdateProgressHandler.sendEmptyMessage(UPLOADING);
                                if(countUpload == lengthTotal){
                                    // 如果已经下载完毕跳出循环
                                    mUpdateProgressHandler.sendEmptyMessage(UPLOAD_FINISH);
                                }
                            }

                            @Override
                            public void onUploadFail(TicketOffline ticket) {
                                if(!failUploadList.contains(ticket)) {
                                    failUploadList.add(ticket);
                                }
                                countUpload ++;
                                // 获取当前下好的文件占总文件的多少比率
                                mProgress = (int) (((float) countUpload / lengthTotal) * 100);
                                // 给Handler发送信息更新进度条
                                mUpdateProgressHandler.sendEmptyMessage(UPLOADING);
                                if(countUpload == lengthTotal){
                                    // 如果已经下载完毕跳出循环
                                    mUpdateProgressHandler.sendEmptyMessage(UPLOAD_FINISH);
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void upload_offline_ticket(final TicketOffline ticket, final UpLoadDataListener listener) {
        PosHttpManager.offlineUploadeData(ticket,new OkHttpUtils.ResultCallback() {
            @Override
            public void onSuccess(JsonObject response) {
                BaseResponse<LoadConfig> baseResponse = BaseResponse.fromJson(response.toString(), LoadConfig.class);
                if(baseResponse.getCode().equals("0")){
                    //更新POS_TJSC表中的标记BJ为1上传成功
                    OfflineManager.updateOfflineTicketStatus(ticket.getOrderNo());
                    listener.onUploadSuccess(ticket);
                }else{
                    OfflineManager.updateOfflineTicketUploadNum(ticket.getOrderNo());
                    listener.onUploadFail(ticket);
                }
            }
            @Override
            public void onFailure(String msg) {
                OfflineManager.updateOfflineTicketUploadNum(ticket.getOrderNo());
                listener.onUploadFail(ticket);
            }
        });
    }

    interface UpLoadDataListener {
        void onUploadSuccess(TicketOffline ticket);
        void onUploadFail(TicketOffline ticket);
    }
}
